/*
 * Window.cpp
 *
 *  Created on: 26-nov.-2013
 *      Author: Axel
 */

#include "Window.h"

#include <iostream>
#include <stdlib.h>
#include <GL/glew.h>
#include <glfw3.h>

//constructor, sets the height, width and title
Window::Window(int width, int height, char* title) {
	WIDTH = width;
	HEIGHT = height;
	TITLE = title;

	init();
}

//destructor
Window::~Window() {
	destroy();
}

//check if the window is closed
bool Window::closeWindow() {
	return glfwWindowShouldClose(window);
}

//swap screen buffer
void Window::swapBuffer() {
	glfwSwapBuffers(window);
}

//handle glfw input
void Window::handleInput() {
	glfwPollEvents();
}

//getter for the window
GLFWwindow* Window::getWindow() {
	return window;
}

//intialise the window
void Window::init() {
	//first glfw
	initWithGLFW();
	//init glew
	initGlew();
}

// Error callback function prints out any errors from GFLW to the console
static void error_callback( int error, const char *description ) {
    std::cout << error << '\t' << description << std::endl;
}

void Window::initWithGLFW() {
	//set a correct error callback
	glfwSetErrorCallback( error_callback );

	 // Initialize the library
    if (!glfwInit()) {
    	std::cout << "error: can't initiate glfw";
    	exit(-1);
	}

    //set the major version (preffered) and minor (fallback) version of Opengl
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3.3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    //glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);
    //set the profiles to use
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
    glfwWindowHint(GLFW_SAMPLES,4);

    // Create a windowed mode window
    window = glfwCreateWindow(WIDTH, HEIGHT, "AxeEngine v1.05", NULL, NULL);
    //else print error
    if (!window) {
    	std::cout << "error opening the glfw window";
        glfwTerminate();
        exit(-1);
    }

	//create OpenGL context
	glfwMakeContextCurrent(window);
}

//initialise glew
void Window::initGlew() {
	//needs to be true to be able to use OpenGL 4
	glewExperimental=GL_TRUE;
	//init glew
	GLenum res = glewInit();
	//else display error
    if (res) {
      std::cout << "Error: " << glewGetErrorString(res);
      exit(-1);
    }
}

//destroy the window
void Window::destroy(){
	glfwTerminate();
}

//turn vsync on
void Window::VSyncOn() {
	glfwSwapInterval(1);
}

//turn vsync off
void Window::VSyncOff() {
	glfwSwapInterval(0);
}

